Ext.app.CookieWindow = function(config) {
    Ext.apply(this, config);

    this.addEvents({
        flowEnd : true
    });

    // Copy configured listeners into *this* object so that the base class's
    // constructor will add them.
    this.listeners = config.listeners;

    Ext.app.CookieWindow.superclass.constructor.call(this);
    this.init();
};

Ext.extend(Ext.app.CookieWindow, Ext.util.Observable, {

    init : function() {
    },

    createWindow : function(pageName, cookieWizardConfig, paracol) {
        Ext.BLANK_IMAGE_URL = '../extjs/resources/images/default/s.gif';

        if (!cookieWizardConfig) {
            // default wizard configuration
            cookieWizardConfig = {
                extButtons: []
            }
        }

        var desktop = this.app.desktop;

        var mainPanel;
        var sbar;

        Ext.QuickTips.init();

        var _this = this;

        function fireFlowEnd() {
            _this.fireEvent("flowEnd", {});
        }


        var resultLabel = new Ext.form.Label({
        });

        var resultPanel = new Ext.FormPanel({
            hidden: true,
            labelWidth: 75, // label settings here cascade unless overridden
            frame:true,
            defaultType: 'textfield',
            style: 'margin-bottom: 0px',

            items: [ resultLabel ],
            cls: 'cookieForm',

            onResult: function(content, context) {
                resultLabel.setText(content, false);
                if (context.canMoveBack) {
                    prevBtn.show();
                } else {
                    prevBtn.hide();
                }
            }

        });


        var nextBtn = new Ext.Button({
            text: 'Next',
            handler: function(btn, ev) {
                paracol.consumeCookie(mainPanel.getCookieFields(), mainPanel);
            }
        });
        var prevBtn = new Ext.Button({
            text: 'Previous',
            handler: function(btn, ev) {
                paracol.unconsumeCookie(mainPanel);
            }
        });
        var closeHandler = function(btn, ev) {
            mainPanel.close();
        };
        var cancelBtn = new Ext.Button({
            text: 'Close',
            handler: closeHandler
        });
        var finishBtn = new Ext.Button({
            text: 'Execute',
            hidden: true,
            handler: function(btn, ev) {
                window.open('disp/?msgType=Execute', 'Executing Instance', 'width=400,height=200,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes)');
                //paracol.execute(mainPanel);
            }
        });


        var contextMenu = new Ext.menu.Menu({
            items: [],

            onHints: function(items, context, data) {
                // sloučit hlavní a položkové menu
                this.removeAll();
                this.add(items);
                this.showAt(data.clickPosition);
                this.hintContext = data;
            }
        });
        contextMenu.addListener("click", function(menu, item) {
            var subject = contextMenu.hintContext.selectedField;
            paracol.openHint(mainPanel, item, subject);
        });
        contextMenu.addListener("mouseover", function(menu, ev, item) {
            sbar.setDescription(item);
        });

        var formPanel = new Ext.FormPanel({
            hidden: true,
            labelWidth: 75, // label settings here cascade unless overridden
            url:'save-form.php',
            frame:true,
            defaultType: 'textfield',
            style: 'margin-bottom: 0px',

            //width: 550,
            //height: 195,

            items: [],
            cls: 'cookieForm',

            onEditCookie: function(fields) {
                this.removeAll();
                this.add(fields);

                this.doLayout();
                if (fields.length > 0) {
                    fields[0].focus();
                }
            }

        });

        // this function finalizes the main form's layout
        var initLayout = function(c, l) {
            for (k = 0; k < mainPanel.getCookieFields().length; k++) {
                var cookieField = mainPanel.getCookieFields()[k];

                // install the context menu on the field
                cookieField.getEl().on("contextmenu", function(ev) {
                    var selFld = Ext.ComponentMgr.get(ev.getTarget().id);
                    paracol.getHints(mainPanel, selFld.name, {
                        selectedField : selFld.name,
                        clickPosition : ev.getXY()
                    });
                }, this, {stopEvent: true});

                // highlight the field if it is selected as a parameter
                if (cookieField.messageValue && cookieField.messageValue.MementoInfoForField) {
                    if (cookieField.messageValue.MementoInfoForField.isParameter) {
                        cookieField.addClass("x-memento-parameter-field-show");
                    } else {
                        cookieField.removeClass("x-memento-parameter-field-show");
                    }
                }

                // validation: highlight the field if its content is not valid
                if (cookieField.messageValue && cookieField.messageValue.ValidationInfo && !cookieField.messageValue.ValidationInfo.isValid) {
                    cookieField.markInvalid(cookieField.messageValue.ValidationInfo.message);
                } else if (cookieField.messageValue && cookieField.messageValue.CommonMetaData) {
                    // tooltips
                    var meta = cookieField.messageValue.CommonMetaData;

                    if (meta.title) {
                        cookieField.fieldLabel = meta.title;
                    }

                    Ext.QuickTips.register({
                        target: cookieField.id,
                        title: meta.title,
                        text: meta.description,
                        width: 100,
                        dismissDelay: 10000 // Hide after 10 seconds hover
                    });
                }

                cookieField.addListener("focus", function(field) {
                    sbar.setDescription(field);
                });
                cookieField.addListener("blur", function(field) {
                    sbar.clearStatus();
                });

            }
        };

        var menuBtn = new Ext.Button({
            text:'Menu'
            //                        ,
            //                        menu: menu  // assign menu by instance
        });
        menuBtn.addListener("click", function(btn, ev) {
            paracol.getHints(mainPanel, null, {
                clickPosition : ev.getXY()
            });
        });

        // constructing the buttons set
        var buttonsSet = [];
        if (!cookieWizardConfig.prevButtonDisabled) buttonsSet[buttonsSet.length] = prevBtn;
        if (!cookieWizardConfig.nextButtonDisabled) buttonsSet[buttonsSet.length] = nextBtn;
        if (!cookieWizardConfig.cancelButtonDisabled) buttonsSet[buttonsSet.length] = cancelBtn;
        if (!cookieWizardConfig.finishButtonDisabled) buttonsSet[buttonsSet.length] = finishBtn;
        if (!cookieWizardConfig.menuButtonDisabled) buttonsSet[buttonsSet.length] = menuBtn;

        sbar = new Ext.ux.StatusBar({
            //renderTo: 'basic',
            id: 'basic-statusbar',
            //width: 550,
            // defaults to use when the status is cleared:
            defaultText: 'Ready',
            //defaultIconCls: 'default-icon',

            // values to set initially:
            text: 'Ready',
            iconCls: 'x-status-valid',

            setDescription: function(item) {
                if (item && item.messageValue && item.messageValue.CommonMetaData &&
                        item.messageValue.CommonMetaData.description) {
                    this.setStatus({
                        text: item.messageValue.CommonMetaData.description,
                        //iconCls: 'x-status-error',
                        clear: true // auto-clear after a set interval
                    });
                } else {
                    this.clearStatus();
                }
            },

            items: buttonsSet
//            items: [
//                prevBtn,
//                nextBtn,
//                cancelBtn,
//                finishBtn,
//                menuBtn
//            ]
        });

        // extension buttons
        if (cookieWizardConfig.extButtons) {
            for (var i = 0; i < cookieWizardConfig.extButtons.length; i++) {
                // wrap the handler of the extension button so that it can receive the reference to the main panel
                // as the third argument
                var extButton = cookieWizardConfig.extButtons[i];
                var origHandler = extButton.handler;
                extButton.handler = function(btn, ev) {
                    origHandler(btn, ev, mainPanel);
                };
                sbar.add(extButton);
            }
        }

        //Ext.get(formPanel.id).setStyle("margin-bottom", "0px");

        Ext.QuickTips.register({
            target: 'timeFld1',
            title: 'My Tooltip',
            text: 'This tooltip was added in code',
            width: 100,
            dismissDelay: 10000 // Hide after 10 seconds hover
        });

        paracol.addHttpListener({
            onRequestSent: function(message) {
                var sb = Ext.getCmp('basic-statusbar');
                // Set the status bar to show that something is processing:
                if (sb) {
                    sb.showBusy();
                }
            },

            onResponseReceived: function(message) {
                var sb = Ext.getCmp('basic-statusbar');
                // once completed
                if (sb) {
                    sb.clearStatus();
                }
            }
        });

        // create the window on the first click and reuse on subsequent clicks
        //mainPanel = new Ext.Window({
        mainPanel = desktop.createWindow({
            id: "CookieWindow",
            shim: false,
            animCollapse: false,
            constrainHeader: true,

            layout: 'fit',

            width:500,
            closeAction:'close',
            plain: true,
            modal: true,

            title: 'ChloroForm',
            bbar: sbar,
            items:[
                formPanel,
                resultPanel
            ],

            getCookieFields: function() {
                return formPanel.items.items;
            },

            onEditCookie: function(msg) {
                var fields = msg.fields;
                var context = msg.context;
                this.setTitle("ChloroForm - " + context.name + "(" + context.page + ")");

                formPanel.onEditCookie(fields);
                formPanel.show();
                resultPanel.hide();
                if (context.canMoveBack) {
                    prevBtn.show();
                } else {
                    prevBtn.hide();
                }
                if (!cookieWizardConfig.nextButtonDisabled) nextBtn.show();
                if (!cookieWizardConfig.cancelButtonDisabled) cancelBtn.show();
                finishBtn.hide();

            },

            onHints: function(msg, data) {
                contextMenu.onHints(msg.items, msg.context, data);
            },

            onResultStarterReady: function(msg) {
                var context = msg.context;
                this.setTitle("ChloroForm - " + context.name);

                formPanel.hide();
                resultPanel.show();
                nextBtn.hide();
                //prevBtn.hide();
                cancelBtn.show();
                if (!cookieWizardConfig.finishButtonDisabled) finishBtn.show();
            },

            onResult: function(msg) {
                var content = msg.content;
                var context = msg.context;
                this.setTitle(context.name);
                this.onResultStarterReady({context: msg.context});
                resultPanel.onResult(content, context);
            },

            onEnd: function(msg) {
//                mainPanel.close();
//                mainPanel = null;
//                fireFlowEnd();
            }
        });


        formPanel.addListener("afterlayout", initLayout);

        //initLayout();

        paracol.startEdit("", pageName, mainPanel);

        mainPanel.on("close", function() {
            paracol.closeFlow();
            fireFlowEnd();
            mainPanel = null;
        });
        mainPanel.show(this);

        return mainPanel;
    }

});